package com.example.demo.controller;

import com.example.demo.model.Configuration;
import com.example.demo.model.KafkaExportConfig;
import com.example.demo.service.ConfigurationService;
import com.example.demo.service.DataGeneratorService;
import com.example.demo.service.DataExportService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 配置管理控制器
 * 提供配置的CRUD接口和数据生成接口
 */
@RestController
@RequestMapping("/api/configurations")
@CrossOrigin(origins = "http://localhost:19999")
@Slf4j
public class ConfigurationController {
    
    @Autowired
    private ConfigurationService configurationService;
    
    @Autowired
    private DataGeneratorService dataGeneratorService;
    
    @Autowired
    private DataExportService dataExportService;
    
    /**
     * 获取所有配置
     * @return 配置列表
     */
    @GetMapping
    public List<Configuration> getAllConfigurations() {
        return configurationService.getAllConfigurations();
    }
    
    /**
     * 创建新配置
     * @param configuration 配置信息
     * @return 创建的配置
     */
    @PostMapping
    public Configuration createConfiguration(@RequestBody Configuration configuration) {
        return configurationService.saveConfiguration(configuration);
    }
    
    /**
     * 根据ID获取配置
     * @param id 配置ID
     * @return 配置信息，如果不存在返回404
     */
    @GetMapping("/{id}")
    public ResponseEntity<Configuration> getConfigurationById(@PathVariable Long id) {
        Configuration configuration = configurationService.getConfigurationById(id);
        return configuration != null ? ResponseEntity.ok(configuration) : ResponseEntity.notFound().build();
    }
    
    /**
     * 删除配置
     * @param id 配置ID
     * @return 空响应
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteConfiguration(@PathVariable Long id) {
        configurationService.deleteConfiguration(id);
        return ResponseEntity.ok().build();
    }
    
    /**
     * 根据配置生成数据
     * @param id 配置ID
     * @return 生成的数据列表
     */
    @PostMapping("/{id}/generate")
    public ResponseEntity<List<Map<String, String>>> generateData(@PathVariable Long id) {
        log.info("收到生成数据请求 - 配置ID: {}", id);
        Configuration config = configurationService.getConfigurationById(id);
        if (config == null) {
            log.warn("未找到配置 - ID: {}", id);
            return ResponseEntity.notFound().build();
        }
        List<Map<String, String>> generatedData = dataGeneratorService.generateData(config);
        return ResponseEntity.ok(generatedData);
    }
    
    /**
     * 导出Excel文件
     * @param id 配置ID
     * @return Excel文件的字节流
     */
    @GetMapping("/{id}/excel")
    public ResponseEntity<byte[]> downloadExcel(@PathVariable Long id) {
        Configuration config = configurationService.getConfigurationById(id);
        if (config == null) {
            return ResponseEntity.notFound().build();
        }
        
        try {
            List<Map<String, String>> data = dataGeneratorService.generateData(config);
            byte[] excelBytes = dataGeneratorService.generateExcel(data, config.getFields());
            
            return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=generated_data.xlsx")
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(excelBytes);
        } catch (IOException e) {
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 更新配置
     * @param id 配置ID
     * @param configuration 更新的配置信息
     * @return 更新后的配置
     */
    @PutMapping("/{id}")
    public ResponseEntity<Configuration> updateConfiguration(
        @PathVariable Long id,
        @RequestBody Configuration configuration
    ) {
        Configuration existingConfig = configurationService.getConfigurationById(id);
        if (existingConfig == null) {
            return ResponseEntity.notFound().build();
        }
        
        // 确保ID一致
        configuration.setId(id);
        Configuration updatedConfig = configurationService.saveConfiguration(configuration);
        return ResponseEntity.ok(updatedConfig);
    }
    
    /**
     * 导出数据文件（支持多种格式）
     * @param id 配置ID
     * @param format 导出格式（csv/json）
     * @return 文件的字节流
     */
    @GetMapping("/{id}/export")
    public ResponseEntity<byte[]> exportData(
        @PathVariable Long id,
        @RequestParam String format
    ) {
        log.info("收到导出请求 - 配置ID: {}, 格式: {}", id, format);
        
        Configuration config = configurationService.getConfigurationById(id);
        if (config == null) {
            log.warn("未找到配置 - ID: {}", id);
            return ResponseEntity.notFound().build();
        }
        
        try {
            List<Map<String, String>> data = dataGeneratorService.generateData(config);
            byte[] fileBytes;
            String fileName;
            String contentType;

            if ("csv".equalsIgnoreCase(format)) {
                log.info("生成CSV格式文件");
                fileBytes = dataGeneratorService.generateCsvBytes(data, config.getFields());
                fileName = "generated_data.csv";
                contentType = "text/csv";
            } else if ("json".equalsIgnoreCase(format)) {
                log.info("生成JSON格式文件");
                fileBytes = dataGeneratorService.generateJsonBytes(data);
                fileName = "generated_data.json";
                contentType = "application/json";
            } else {
                log.warn("不支持的导出格式: {}", format);
                return ResponseEntity.badRequest().build();
            }
            
            log.info("文件生成完成 - 类型: {}, 大小: {} bytes", contentType, fileBytes.length);
            return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName)
                .contentType(MediaType.parseMediaType(contentType + ";charset=utf-8"))
                .body(fileBytes);
        } catch (IOException e) {
            log.error("导出文件时发生错误", e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 导出数据到Kafka
     */
    @PostMapping("/{id}/export/kafka")
    public ResponseEntity<Map<String, Object>> exportToKafka(
        @PathVariable Long id,
        @RequestBody KafkaExportConfig kafkaConfig
    ) {
        Configuration config = configurationService.getConfigurationById(id);
        if (config == null) {
            return ResponseEntity.notFound().build();
        }

        try {
            List<Map<String, String>> data = dataGeneratorService.generateData(config);
            int successCount = dataExportService.exportToKafka(data, kafkaConfig);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("totalCount", data.size());
            result.put("successCount", successCount);
            result.put("topic", kafkaConfig.getTopic());
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("导出到Kafka失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
} 